package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

@Controller
@RequestMapping("/cart")
@SessionAttributes({"cart"})
public class CartController {

    @Autowired
    private Cart cart;

    @Autowired
    private CatalogService catalogService;

    public Cart getCart() {
        return cart;
    }

    public void setCart(Cart cart) {
        this.cart = cart;
    }

    @GetMapping("/viewCart")
    public String viewCart(Model model) {
        model.addAttribute("cart",cart);
        return "Cart/cart";
    }

    @PostMapping("/updateCartQuantities")
    public String updateCartQuantities(HttpServletRequest request, Model model) {
        Iterator<CartItem> cartItems = getCart().getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                int quantity = Integer.parseInt(request.getParameter(itemId));
                getCart().setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }
        model.addAttribute("cart",cart);
        return "Cart/cart";
    }

    @GetMapping("/removeItemFromCart")
    public String removeItemFromCart(String workingItemId, Model model){
        Item item = cart.removeItemById(workingItemId);
        model.addAttribute("cart",cart);
        if(item == null){
            model.addAttribute("msg", "Attempted to remove null CartItem from Cart.");
            return "common/error";
        }else{
            return "cart/cart";
        }
    }

    @GetMapping("/askCheckOut")
    public String askCheckOut(Model model){
        model.addAttribute("cart",cart);
        return "Cart/checkout";
    }

}


